package com.xd.comment2.controller;

import com.xd.comment2.entity.Comment;
import com.xd.comment2.service.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Controller
public class PageController {
    @Autowired
    private Service service;

    @Autowired
    private MongoTemplate mongoTemplate;

    @RequestMapping("/index")
    public String index(){
        return "index";
    }

    @RequestMapping("/findAll")
    @ResponseBody
    public Map<String,Object> findAll(){
        Map<String,Object> map=new HashMap<>();
        Query query = new Query();
        query.addCriteria(Criteria.where("parentid").is("0"));
        Query query2 = new Query();
        query2.addCriteria(Criteria.where("parentid").nin("0"));
        List<Comment> comments2 = mongoTemplate.find(query2, Comment.class);
        int num=comments2.size();
        System.out.println(num);
        /*map.put("num",num);*/
        //所有数据
        List<Comment> comments = mongoTemplate.find(query, Comment.class);
        //总数据条数
        System.out.println(comments.size());
        for (int i = 1; i <= comments.size() ; i++) {
            Criteria c1= Criteria.where("id").is(""+i);
            Criteria c2= Criteria.where("parentid").is(""+i);
            Criteria cr = new Criteria();
            Query query1 = new Query(cr.orOperator(c1,c2));
            List<Comment> comments1 = mongoTemplate.find(query1, Comment.class);
            map.put("data"+i,comments1);
        }
        /*map.put("num",comments2.size());*/
        return map;
    }

    @RequestMapping("/reply")
    @ResponseBody
    public List<Comment> reply(String id){
        System.out.println(id);
        Random random = new Random();
        int rad = random.nextInt(100);
        Comment comment=new Comment();
        comment.setContent("嘻嘻"+rad);
        if (!(id.equals(null))){
            comment.setParentid(id);
            service.saveComment(comment);
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("parentid").is(id));
        List<Comment> comments = mongoTemplate.find(query, Comment.class);
        return comments;
    }
}
